<template>
  <el-dialog v-model="visible" title="审核申请" top="0vh" :close-on-click-modal="false" @close="handleClose">
    <div class="review-content">
      <!-- 申请信息概览 -->
      <el-card shadow="always" class="applicant-overview">
        <template #header>
          <el-space style="width: 100%">
            <el-icon><User /></el-icon>
            <span>申请信息概览</span>
          </el-space>
        </template>
        <el-row justify="space-around" :gutter="20">
          <el-col :span="12">
            <el-space>
              <el-avatar :size="50" :src="applicantData.avatar" />
              <div>
                <div class="applicant-name">{{ applicantData.name }}</div>
              </div>
            </el-space>
          </el-col>
          <el-col :span="12">
            <el-space direction="vertical" alignment="flex-start">
              <el-space direction="horizontal">
                <el-icon><Calendar /></el-icon>
                <el-text type="primary">{{ formatDate(applicantData.createTime) }}</el-text>
              </el-space>
              <el-space direction="horizontal">
                <el-icon><Document /></el-icon>
                <el-tag :type="getStatusType(applicantData.status)">
                  {{ getStatusText(applicantData.status) }}
                </el-tag>
              </el-space>
            </el-space>
          </el-col>
        </el-row>
      </el-card>

      <!-- 审核操作 -->
      <el-card shadow="always" class="audit-operation">
        <template #header>
          <el-space>
            <el-text type="danger">*</el-text>
            <el-icon><Check /></el-icon>
            <div>审核操作</div>
          </el-space>
        </template>
        <el-form ref="formRef" :model="formData" :rules="formRules">
          <el-form-item prop="status" required>
            <el-radio-group v-model="formData.status" fill="rgb(0, 0, 0)" style="width: 100%" size="large">
              <el-radio value="1" style="min-height: 60px; width: 100%; margin: 0" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><Check /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="success">审核通过</el-text>
                      <el-text type="info">申请材料齐全，符合要求，予以通过</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
              <el-radio value="2" style="min-height: 60px; width: 100%; margin: 0; margin-top: 10px" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><Close /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="danger">拒绝申请</el-text>
                      <el-text type="info">申请材料不符合要求，拒绝通过</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
              <el-radio value="3" style="min-height: 60px; width: 100%; margin: 0; margin-top: 10px" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><EditPen /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="warning">需要补充材料</el-text>
                      <el-text type="info">申请材料不完整，需要补充材料</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 审核意见 -->
      <el-card shadow="always" class="audit-opinion">
        <template #header>
          <el-space>
            <el-text type="danger">*</el-text>
            <el-icon><Edit /></el-icon>
            <div>审核意见</div>
          </el-space>
        </template>
        <el-form ref="formRef" :model="formData" :rules="formRules">
          <el-form-item
            prop="checkOpinion"
            required
            :rules="[
              { required: true, message: '请输入审核意见' },
              { max: 400, message: '审核意见不能超过400个字符' },
              { min: 1, message: '审核意见不能少于1个字符' },
              { pattern: /\S/, message: '审核意见不能为空' },
            ]"
          >
            <el-input
              v-model="formData.checkOpinion"
              :show-word-limit="true"
              resize="none"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="400"
              type="textarea"
              placeholder="例如：申请材料齐全，符合要求，予以通过。"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <!-- 提示信息 -->
          <el-alert :closable="false" style="margin-top: 10px">
            <template #default>
              <el-space direction="vertical">
                <el-space>
                  <el-icon color="#ffc345"><Opportunity /></el-icon>
                  <span>提示：请提供具体的审核意见，以便申请人了解审核结果</span>
                </el-space>
              </el-space>
            </template>
          </el-alert>
        </template>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确认审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { AuthenticationResponse } from '@/api/model/authenticationModel';
import { Calendar, Check, Close, Document, Edit, EditPen, Opportunity, User } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import { computed, ref, watch } from 'vue';

// 组件属性
interface Props {
  visible: boolean;
  data: AuthenticationResponse | null;
}

// 组件事件
interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit', data: ReviewFormData): void;
}

// 审核表单数据
interface ReviewFormData {
  status: string; // 改为字符串类型，对应radio的value
  checkOpinion: string;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const formRef = ref<FormInstance>();
const submitting = ref(false);

// 申请人数据
const applicantData = computed(() => props.data || ({} as AuthenticationResponse));

// 表单数据
const formData = ref<ReviewFormData>({
  status: '', // 初始化为空字符串
  checkOpinion: '',
});

// 表单验证规则
const formRules = computed(() => {
  const rules: any = {
    status: [
      {
        validator: (rule: any, value: any, callback: any) => {
          // 检查是否选择了审核状态
          if (!value || value === '') {
            callback(new Error('请选择审核状态'));
          } else {
            callback();
          }
        },
        trigger: 'change',
      },
    ],
  };

  return rules;
});

// 状态相关方法
const getStatusText = (status: number) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
    3: '需要补充材料',
    4: '审核中',
  };
  return statusMap[status] || '未知状态';
};

// Element Plus 标签类型映射
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info',
    4: 'primary',
  };
  return typeMap[status] || 'default';
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
    .replace(/\//g, '/');
};

// 状态变化处理
const handleStatusChange = (value: string) => {
  console.log('状态变化:', value, '类型:', typeof value);

  // 清除当前字段的验证状态，让新规则生效
  formRef.value?.clearValidate(['status']);
};

// 监听弹窗显示状态，重置表单
watch(visible, (newVisible) => {
  if (newVisible) {
    resetForm();
  }
});

// 重置表单
const resetForm = () => {
  formData.value = {
    status: '', // 重置为空字符串
    checkOpinion: '',
  };
  formRef.value?.clearValidate();
};

// 提交审核
const handleSubmit = async () => {
  try {
    // 表单验证
    console.log('提交前 formData:', formData.value);
    console.log('提交前 status 值:', formData.value.status, '类型:', typeof formData.value.status);

    const valid = await formRef.value?.validate();
    console.log('valid', valid);

    if (!valid) {
      console.log('表单验证失败，不提交');
      return;
    }

    submitting.value = true;

    // 构建提交数据
    const submitData: ReviewFormData = {
      status: formData.value.status,
      checkOpinion: formData.value.checkOpinion.trim(),
    };

    // 触发提交事件
    emit('submit', submitData);
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitting.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};
</script>

<style scoped lang="less">
.review-content {
  padding: 0;

  // 申请信息概览卡片
  .applicant-overview {
    margin-bottom: 16px;

    .applicant-name {
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 4px;
    }
  }

  // 审核操作卡片
  .audit-operation {
    margin-bottom: 16px;
  }

  // 审核意见卡片
  .audit-opinion {
    margin-bottom: 16px;
  }
}

/**
 * 审核操作，对应选中的颜色变化
 */
/* 审核通过 */
:deep(.el-radio.is-bordered.is-checked.el-radio--large:nth-child(1)) {
  background-color: #f0f9f6;
  border-color: #00a870;
}

/* 拒绝申请 */
:deep(.el-radio.is-bordered.is-checked.el-radio--large:nth-child(2)) {
  border-color: #f56c6c;
  background-color: #fff0f0;
}

/* 待补充 */
:deep(.el-radio.is-bordered.is-checked.el-radio--large:nth-child(3)) {
  border-color: #e6a23c;
  background-color: #fff8e6;
}

// 响应式设计
@media (max-width: 768px) {
  .review-content {
    .applicant-overview {
      .el-row {
        flex-direction: column;
        gap: 16px;
      }
    }
  }
}
</style>
